package cn.ecut.dao;

import cn.ecut.exception.DaoException;
import cn.ecut.model.User;
import cn.ecut.utils.JDBCHelper;
import cn.ecut.utils.TableNames;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    private String column = " userid,username,userpassword ";

    public User loadByUserId(Integer userId) {
        String SQL = "select * from " + TableNames.USER_TABLE_NAME + " where userid = ? ";
        ResultSet resultSet = JDBCHelper.query(SQL, userId);
        List<User> users = warp(resultSet);
        if (users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    public List<User> loadByUsername(User user) {
        String SQL = "select * from " + TableNames.USER_TABLE_NAME + " where username = ? ";
        ResultSet resultSet = JDBCHelper.query(SQL, user.getUsername());
        List<User> users = warp(resultSet);
        return users;
    }

    public boolean saveUser(User user) {
        String SQL = "insert into " + TableNames.USER_TABLE_NAME + " values ( ? , ? , ?, ?, ?, ?)";
        return JDBCHelper.execute(SQL, user.getUserid(), user.getUsername(), user.getUserpassword(),
                user.getUserphone(), user.getUsergender(), user.getUseremail());
    }

    private List<User> warp(ResultSet resultSet) throws DaoException {
        List<User> list = new ArrayList<>();
        try {
            while (resultSet.next()) {
                User u = new User();
                u.setUserid(resultSet.getInt("userid"));
                u.setUsername(resultSet.getString("username"));
                u.setUserpassword(resultSet.getString("userpassword"));
                u.setUserphone(resultSet.getString("userphone"));
                u.setUsergender(resultSet.getString("usergender"));
                u.setUseremail(resultSet.getString("useremail"));
                list.add(u);
            }
        } catch (SQLException e) {
            throw new DaoException("数据封装出错。");
        }
        return list;
    }
}
